package com.atguigu.gmall.order.consumer;

import com.atguigu.gmall.order.service.OrderInfoService;
import com.atguigu.gmall.rebbit.constant.MqConst;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class CancelOrderConsumer {

    @Autowired
    private OrderInfoService orderInfoService;

    @RabbitListener(queues = MqConst.QUEUE_ORDER_CANCEL1)
    public void cancelOrder(Long orderId, Message message, Channel channel){
        String userId = message.getMessageProperties().getUserId();
        String uuid = message.getMessageProperties().getHeader("spring_returned_message_correlation");
        orderInfoService.cancelOrder(orderId,uuid);
        System.out.println("取消订单接收的"+userId);
        try {

            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            //e.printStackTrace();
            if(!message.getMessageProperties().isRedelivered()){
                try {
                    channel.basicNack(message.getMessageProperties().getDeliveryTag(),true,false);
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }else {
                try {
                    channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
                } catch (IOException exc) {
                    exc.printStackTrace();
                }
            }

        }
    }

}
